package com.atguigu.gmall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.BaseManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class BaseManageServiceImpl implements BaseManageService {
    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;

    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;

    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;

    @Autowired
    private SpuInfoMapper spuInfoMapper;

    @Autowired
    private  BaseSaleAttrMapper baseSaleAttrMapper;


    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;

    @Autowired
    private SpuImageMapper spuImageMapper;

    @Autowired
    private  SpuPosterMapper spuPosterMapper;

    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;

    @Autowired
    private SkuInfoMapper skuInfoMapper;

    @Autowired
    private  SkuImageMapper skuImageMapper;

    @Autowired
    private  SkuSaleAttrValueMapper skuSaleAttrValueMapper;

    @Autowired
    private  SkuAttrValueMapper skuAttrValueMapper;

    @Autowired
    private  BaseCategoryViewMapper baseCategoryViewMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private BaseTradeMarkMapper baseTrademarkMapper;


    /**
     * 查询一级分类数据
     * @return
     */
    @Override
    public List<BaseCategory1> getCategory1() {
        List<BaseCategory1> baseCategory1s = baseCategory1Mapper.selectList(null);
        return baseCategory1s;
    }
    /**
     * 查询二级分类数据
     * @return
     */
    @Override
    public List<BaseCategory2> getCategory2(long category1Id) {
        QueryWrapper<BaseCategory2> wrapper = new QueryWrapper<>();
        wrapper.eq("category1_id",category1Id);

        return baseCategory2Mapper.selectList(wrapper);
    }
    /**
     * 查询三级分类数据
     * @return
     */
    @Override
    public List<BaseCategory3> getCategory3(Long category2Id) {
        QueryWrapper<BaseCategory3> wrapper = new QueryWrapper<>();
        wrapper.eq("category2_id",category2Id);
        return baseCategory3Mapper.selectList(wrapper);
    }
    /**
     * 根据分类Id 获取平台属性集合
     */
    @Override
    public List<BaseAttrInfo> attrInfoList(Long category1Id, Long category2Id, Long category3Id) {
        return baseAttrInfoMapper.selectAttrInfoList(category1Id,category2Id,category3Id);
        //  根据分析可能需要具备的知识点：mybatis的动态sql 标签！
        //  多表关联查询：因此 使用*Mapper.xml
        //  开发的默认规则： service 层 ；get  save mapper层；select insert
    }
    /**
     * 保存平台属性
     */
    @Override
    @Transactional(rollbackFor = Exception.class) // 有异常就回滚！
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        if (baseAttrInfo.getId()==null){
            //插入数据
            baseAttrInfoMapper.insert(baseAttrInfo);
        }else {
            baseAttrInfoMapper.updateById(baseAttrInfo);
        }
        //base_attr_value 先执行删除   之后再插入
        QueryWrapper<BaseAttrValue> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_id",baseAttrInfo.getId());
        baseAttrValueMapper.delete(queryWrapper);
        //获取数组
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        //  普通循环
        for (BaseAttrValue baseAttrValue : attrValueList) {
            //  attrId 传递的时候是null
            baseAttrValue.setAttrId(baseAttrInfo.getId());
            baseAttrValueMapper.insert(baseAttrValue);
        }
    }
    /**
     *根据平台属性Id 获取到平台属性值集合
     */
    @Override
    public List<BaseAttrValue> getAttrValueList(Long attrId) {
        QueryWrapper<BaseAttrValue> wrapper = new QueryWrapper<>();
        List<BaseAttrValue> baseAttrValueList = baseAttrValueMapper.selectList(wrapper);
        return baseAttrValueList;
    }
    /**
     *根据平台属性Id 获取到平台属性
     */
    @Override
    public BaseAttrInfo getAttrInfoList(Long attrId) {
        QueryWrapper<BaseAttrInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",attrId);
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(attrId);
        if (baseAttrInfo!=null){
            baseAttrInfo.setAttrValueList(getAttrValueList(attrId));
        }
        return baseAttrInfo;
    }
    /**
     * 获取spu    分页列表spu
     * @param iPage
     * @param spuInfo
     * @return
     */
    @Override
    public IPage getSpuInfoPage(IPage iPage, SpuInfo spuInfo) {
        QueryWrapper<SpuInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category3_id",spuInfo.getCategory3Id());
        queryWrapper.orderByDesc("id");
        IPage iPage1 = spuInfoMapper.selectPage(iPage, queryWrapper);
        return iPage1;
    }

    /**
     * 获取销售属性数据
     * @return
     */
    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        List<BaseSaleAttr> baseSaleAttrList = baseSaleAttrMapper.selectList(null);
        return baseSaleAttrList;
    }
    /**
     * spu大保存
     * @param spuInfo
     * @return
     * 多表插入要加入事物
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveSpuInfo(SpuInfo spuInfo) {
         /*
        spuInfo;	商品表
        spuImage;	商品图片表
        spuSaleAttr;	销售属性
        spuSaleAttrValue;	销售属性值
        spuPoster;	商品海报
         */
         //插入商品表
        spuInfoMapper.insert(spuInfo);
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        //插入商品图片表
        if (!CollectionUtils.isEmpty(spuImageList)){
            spuImageList.stream().forEach(spuImage -> {
                spuImage.setSpuId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            });
        }
        //插入商品海报表
        List<SpuPoster> spuPosterList = spuInfo.getSpuPosterList();
        if (!CollectionUtils.isEmpty(spuPosterList)){
            spuPosterList.stream().forEach(spuPoster -> {
                spuPoster.setSpuId(spuInfo.getId());
                spuPosterMapper.insert(spuPoster);
            });
        }
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        //插入销售属性
        if (!CollectionUtils.isEmpty(spuSaleAttrList)) {
            spuSaleAttrList.stream().forEach(spuSaleAttr -> {
                spuSaleAttr.setSpuId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                //插入销售属性值表
                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)) {
                    spuSaleAttrValueList.stream().forEach(spuSaleAttrValue -> {
                        spuSaleAttrValue.setSpuId(spuInfo.getId());
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    });
                }
            });

        }
    }
    /**
     * spuImage信息显示
     */
    @Override
    public List<SpuImage> getSpuImageList(Long spuId) {
        QueryWrapper<SpuImage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("spu_id",spuId);
        queryWrapper.orderByDesc("id");
        List<SpuImage> spuImageList = spuImageMapper.selectList(queryWrapper);
        return spuImageList;
    }
    /**
     * 根据spuId 查询销售属性
     */
    @Override
    public List<SpuSaleAttr> getSpuSaleAttrList(Long spuId) {
        /**
         * 多表关联   调用mapper
         */
        List<SpuSaleAttr> spuSaleAttrList=spuSaleAttrMapper.selectSpuSaleAttrList(spuId);
        return spuSaleAttrList;
    }
    /**
     * 保存SkuInfo  简称大保存  保存一个sku所有信息
     * @param skuInfo
     * @return
     */
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        /*
            将数据插入数据库表！
            skuInfo:	库存单元表！	记录是哪个spu下的sku!
            skuImage:	库存单元图片表!
            skuSaleAttrValue;	sku 与 销售属性值中间表！
            skuAttrValue:	sku 与平台属性值中间表！
         */
        //首先插入sku_info   因为先插入  才能主键自动获取ID
        skuInfoMapper.insert(skuInfo);
        //插入sku_image
        List<SkuImage> skuImageList = skuInfo.getSkuImageList();
        if (!CollectionUtils.isEmpty(skuImageList)) {
            skuImageList.stream().forEach(skuImage ->
            {
                skuImage.setSkuId(skuInfo.getId());
                skuImageMapper.insert(skuImage);
            });
        }
        //插入    sku_attr_value
        List<SkuAttrValue> skuAttrValueList = skuInfo.getSkuAttrValueList();
        if (!CollectionUtils.isEmpty(skuAttrValueList)) {
            skuAttrValueList.stream().forEach(skuAttrValue -> {
                //  应该能够获取到平台属性名，平台属性值名！
                //  应该页面自动获取！   查询：category3Id 查询到平台属性名！但是绝对找不到要给的属性值名称！
                //  经过分析：可以不用赋值attrName valueName;
            skuAttrValue.setSkuId(skuInfo.getId());
            skuAttrValueMapper.insert(skuAttrValue);
            });
        }
        //插入    sku_sale_attr_value
        List<SkuSaleAttrValue> skuSaleAttrValueList = skuInfo.getSkuSaleAttrValueList();
        if (!CollectionUtils.isEmpty(skuSaleAttrValueList)) {
            skuSaleAttrValueList.stream().forEach(skuSaleAttrValue -> {
                skuSaleAttrValue.setSkuId(skuInfo.getId());
                skuSaleAttrValue.setSpuId(skuInfo.getSpuId());
                skuSaleAttrValueMapper.insert(skuSaleAttrValue);
            });
        }
    }

    @Override
    public IPage getList(Page<SkuInfo> skuInfoPage) {
        QueryWrapper<SkuInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        Page<SkuInfo> skuInfoPage1 = skuInfoMapper.selectPage(skuInfoPage, queryWrapper);
        return skuInfoPage1;
    }
    //上架
    @Override
    public void onSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);
        skuInfoMapper.updateById(skuInfo);
    }
    //下架
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);
        skuInfoMapper.updateById(skuInfo);
    }

    //查询出数据skuInfo  + skuImages
    @Override
    @GmallCache(prefix ="SkuInfo:" )
    public SkuInfo getSkuInfo(Long skuId) {
        //select * from sku_info where id = skuId
        SkuInfo skuInfo = skuInfoMapper.selectOne(new QueryWrapper<SkuInfo>().eq("id", skuId));
        // select * from sku_image where id = skuId
        //避免出现空指针
        if (skuInfo!=null){
            List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId));
            skuInfo.setSkuImageList(skuImageList);
        }

        return skuInfo;
    }

    private SkuInfo getSkuInfoRedisson(Long skuId) {
        try {
            //  定义缓存的key sku:skuId:info
            String skuKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
            SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);
            //判断缓存中是否有数据
            if (skuInfo==null){
                //缓存中没有        走数据库+锁
                String lockKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKULOCK_SUFFIX;
                RLock lock = redissonClient.getLock(lockKey);
                boolean result = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX2, TimeUnit.SECONDS);
                //判断是否加锁成功
                if (result){
                    try {
                        skuInfo = getSkuInfo(skuId);
                        //防止缓存穿透
                        if (skuInfo==null){
                            SkuInfo skuInfo1 = new SkuInfo();
                            this.redisTemplate.opsForValue().set(skuKey,skuInfo1,RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
                            return skuInfo1;
                        }
                        //存入数据库
                        this.redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SKUKEY_TIMEOUT,TimeUnit.SECONDS);
                        return skuInfo;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }finally {
                        lock.unlock();
                    }
                }else {
                    //没抢上锁
                        Thread.sleep(1000);
                        //自旋
                        getSkuInfoRedisson(skuId);
                }
            }else {
                //缓存中有数据
                return skuInfo;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //如果redis宕机
        return getSkuInfoDB(skuId);
    }

    /**
     * //用redis本地锁丰富页面
     * @param skuId
     * @return
     */
    private SkuInfo getSkuInfoByRedisLua(Long skuId) {
        //  定义缓存的key sku:skuId:info
        String skuKey= RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKUKEY_SUFFIX;
        try {
            SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);
            if (skuInfo==null){
                //  说明缓存中没有数据！查询数据库，并添加分布式锁的业务逻辑
                //redis +lua
                String uuid= UUID.randomUUID().toString();
                //加锁
                String lockKey = RedisConst.SKUKEY_PREFIX+skuId+RedisConst.SKULOCK_SUFFIX;
                Boolean flag = this.redisTemplate.opsForValue().setIfAbsent(lockKey, uuid, RedisConst.SKULOCK_EXPIRE_PX1, TimeUnit.SECONDS);
                // set k v ex 30 nx
                // flag=true表示获取到了锁
                if (flag){
                    //执行业务逻辑
                    skuInfo = getSkuInfo(skuId);
                    //防止缓存穿透
                    if (skuInfo==null){
                        SkuInfo skuInfo1 = new SkuInfo();
                        this.redisTemplate.opsForValue().set(skuKey,skuInfo1,RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
                        return skuInfo1;
                    }
                    //如果是数据库中有数据！
                    this.redisTemplate.opsForValue().set(skuKey,skuInfo,RedisConst.SKUKEY_TIMEOUT,TimeUnit.SECONDS);
                    //删除锁对象
                    //准备一个  lua脚本
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                    DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
                        //存储lua脚本
                        redisScript.setScriptText(script);
                        redisScript.setResultType(Long.class);
                        this.redisTemplate.execute(redisScript, Arrays.asList(lockKey),uuid);
                        return skuInfo;
                }else {
                    //  没有获取到锁的人
                    try {
                        Thread.sleep(1000);
                        // 自旋
                        return getSkuInfo(skuId);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }else {
                //缓存不为空
                return skuInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getSkuInfoDB(skuId);
    }

    /**
     * 从数据库中获取数据
     * @param skuId
     * @return
     */
    private SkuInfo getSkuInfoDB(Long skuId) {
        //  获取skuInfo
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);

        //  判断skuInfo 是否为空！
        if (skuInfo !=null){
            //  需要skuImageList
            List<SkuImage> skuImageList = skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId));

            skuInfo.setSkuImageList(skuImageList);
        }

        return skuInfo;
    }



    //获取实时价格
    @Override
    public BigDecimal getSkuPrice(Long skuId) {
        //不需要放到缓存中          但是多线程情况下  需要上锁    本地锁锁不住---因为业务需要是分布式项目   使用需要分布式锁
        RLock lock = redissonClient.getLock(skuId + "lock");
        lock.lock();
        SkuInfo skuInfo=null;
        BigDecimal price = new BigDecimal(0);
        try {
            QueryWrapper<SkuInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id",skuId);
            queryWrapper.select("price");
              skuInfo = skuInfoMapper.selectOne(queryWrapper);
            if (skuInfo!=null){
                price = skuInfo.getPrice();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //解锁
            lock.unlock();
        }
        return price;
    }
    //查询spu海报
    @Override
    @GmallCache(prefix = "SpuPoster:")
    public List<SpuPoster> getSpuPosterBySpuId(Long spuId) {
        return spuPosterMapper.selectList(new QueryWrapper<SpuPoster>().eq("spu_id",spuId));
    }

    //  根据三级分类Id 来获取分类名称等数据！
    @GmallCache(prefix = "CategoryView:")
    @Override
    public BaseCategoryView getCategoryView(Long category3Id) {
        BaseCategoryView baseCategoryView = baseCategoryViewMapper.selectById(category3Id);
        return baseCategoryView;
    }
    //回显销售属性+销售属性值并锁定！
    //  根据spuId,skuId 来获取数据！
    @Override
    @GmallCache(prefix = "SpuSaleAttrList:")
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
      return   spuSaleAttrMapper.getSpuSaleAttrListCheckBySku(skuId,spuId);
    }
    //  获取商品的规格参数，：获取商品的平台属性平台属性值！

    @Override
    @GmallCache(prefix = "getAttrList:")
    public List<BaseAttrInfo> getAttrList(Long skuId) {
      return   baseAttrInfoMapper.getAttrList(skuId);
    }

    //  根据spuId 获取数据！
    @Override
    @GmallCache(prefix = "SkuValueIdsMap:")
    public Map getSkuValueIdsMap(Long spuId) {
        HashMap<Object, Object> hashMap = new HashMap<>();
         List<Map> mapList =skuSaleAttrValueMapper.getSkuValueIdsMap(spuId);
        if (!CollectionUtils.isEmpty(mapList)) {
            mapList.stream().forEach(map -> {
                hashMap.put(map.get("value_ids"),map.get("sku_id"));
            });
        }
        return hashMap;
    }




    @Override
    public List<JSONObject> getBaseCategoryList() {
        //声明一个集合
        List<JSONObject> list = new ArrayList<>();
        //一级    二级  三级分类数据
        //获取到所有的分类数据    base_category_view
        List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(null);
        //分组：先按照一级分类id  进行分组
        // map key = category1Id    value  = List<BaseCategoryView>
        Map<Long, List<BaseCategoryView>> BaseCategory1Map = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        //声明一个index遍历
        int index = 1;
        //循环遍历这个map集合
        Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator = BaseCategory1Map.entrySet().iterator();
        while (iterator.hasNext()){
            //创建一个对象
            JSONObject category1 =new JSONObject();
            //获取到Entry对象
            Map.Entry<Long, List<BaseCategoryView>> entry = iterator.next();
            Long category1Id= entry.getKey();
            List<BaseCategoryView> baseCategoryViewList1 = entry.getValue();
            //一级分类id
            category1.put("categoryId",category1Id);
            //一级分类名称
            category1.put("categoryName",baseCategoryViewList1.get(0).getCategory1Name());
            //表示一级分类的第几项；
            category1.put("index",index);
            /**
             * 一级分类下还有categoryChild  必须知道二级分类数据集合
             * index 迭代
             * */
            index++;
            //获取一级分类下的二级分类数据
            //// map key = category2Id    value  = List<BaseCategoryView>
            Map<Long, List<BaseCategoryView>> BaseCategory2Map = baseCategoryViewList1.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator1 = BaseCategory2Map.entrySet().iterator();
            //  声明一个存储二级分类数据的集合
            List<JSONObject> category2Child = new ArrayList<>();
            while (iterator1.hasNext()){
                JSONObject category2 =new JSONObject();
                Map.Entry<Long, List<BaseCategoryView>> entry1 = iterator1.next();
                Long category2Id = entry1.getKey();
                List<BaseCategoryView> baseCategoryViewList2 = entry1.getValue();
                //2级分类id
                category2.put("categoryId",category2Id);
                //2级分类名称
                category2.put("categoryName",baseCategoryViewList2.get(0).getCategory2Name());
                //存储二级分类数据
                category2Child.add(category2);
                //创建一个集合来存储三级分类数据
                List<JSONObject> category3Child = new ArrayList<>();
                //获取三级分类数据
                baseCategoryViewList2.forEach(baseCategoryView -> {
                    //创建一个对象
                    JSONObject category3 =new JSONObject();
                    category3.put("categoryId",baseCategoryView.getCategory3Id());
                    category3.put("categoryName",baseCategoryView.getCategory3Name());
                    category3Child.add(category3);
                });
                //将三级分类数据保存到二级分类数据中
                category2.put("categoryChild",category3Child);
            }
                //将二级分类数据保存到一级分类数据中
            category1.put("categoryChild",category2Child);
            //把一级分类数据添加到集合中
            list.add(category1);
        }

        return list;
    }

    @Override
    public BaseTrademark getTrademarkByTmId(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);

    }


}
